package com.situ.shoplook.common.util;

import com.situ.shoplook.common.model.Account;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 功能：
 *
 * @author 千堆雪
 * @version 1.0.0
 * <p>
 * created by 千堆雪 on 2024/8/11, last modified by 千堆雪 on 2024/8/11
 */
public class WebAppContext {
    //匿名用户
    private static final Account ANONYMOUS = new Account();
    public static final String CURRENT_LOGIN_ACCOUNT_KEY = "@#CURRENT_LOGIN_ACCOUNT_KEY";
    private static final ThreadLocal<Account> THREAD_LOCAL_ACCOUNT = new ThreadLocal<>();

    static {
        ANONYMOUS.setUsername("anonymous");
    }

    public static Account getCurrentAccount() {
        Account account = THREAD_LOCAL_ACCOUNT.get();
        if (account == null) {
            account = getCurrentAccountFromRequest();
        }
        if (account == null) {
            account = ANONYMOUS;
        }
        return account;
    }

    public static void setCurrentAccount(Account account) {
        THREAD_LOCAL_ACCOUNT.set(account);
    }

    public static void removeCurrentAccount() {
        THREAD_LOCAL_ACCOUNT.remove();
    }

    /**
     * 从session域中获取认证用户
     *
     * @return 认证用户
     */
    private static Account getCurrentAccountFromRequest() {
        RequestAttributes ra = RequestContextHolder.currentRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpSession session = sra.getRequest().getSession();
        return (Account) session.getAttribute(CURRENT_LOGIN_ACCOUNT_KEY);
    }

    /**
     * 响应json数据
     *
     * @param resp 响应对象
     * @param json json
     */
    public static void writeJson(HttpServletResponse resp, String json) throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.write(json);
        out.flush();
    }
}
